﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using NLog;
using TfsGiggle.Core;

namespace TfsGiggle.EngineService
{
    /// <summary>
    /// The service
    /// </summary>
    public partial class TfsGiggleService : ServiceBase
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();
        private CancellationTokenSource _tokenSource = new CancellationTokenSource();
        private WCFUtil _hostService = new WCFUtil();
        private int[] _subscriptionIds;

        /// <summary>
        /// The TfsGiggle service
        /// </summary>
        public TfsGiggleService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Starts all TfsGiggle dependencies
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            _logger.Trace("enter");
            if (args != null && args.Length > 0 && args[0].ToLowerInvariant().Equals("debug"))
            {
                Debugger.Launch();
            }
            Thread serviceThread = new Thread(new ThreadStart(BackgroundStart));
            serviceThread.IsBackground = true;
            serviceThread.Start();
        }

        private void BackgroundStart()
        {
            _logger.Trace("enter");
            const int RetryIntervalInMinutes = 10;
            while (true)
            {
                try
                {
                    var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];
                    var tfsUri = new Uri(ConfigurationManager.AppSettings["TfsUrl"]);
                    var port = Int32.Parse(ConfigurationManager.AppSettings["Port"]);
                    JobManager.Instance.Open(dataDirectory, tfsUri, _tokenSource.Token);
                    var subscriptionUris = _hostService.HostThisService(port);
                    _subscriptionIds = TfsUtil.SubscribeToCheckinEvents(tfsUri, subscriptionUris[0]);
                    break;
                }
                catch (Exception ex)
                {
                    var msg = string.Format("Caught an exception. Will retry to start in {0} minutes", RetryIntervalInMinutes);
                    _logger.ErrorException(msg, ex);
                    Thread.Sleep((int)TimeSpan.FromMinutes(RetryIntervalInMinutes).TotalMilliseconds);
                }
            }
        }

        /// <summary>
        /// Stops all TfsGiggle dependencies
        /// </summary>
        protected override void OnStop()
        {
            _logger.Trace("enter");
            var tfsUri = new Uri(ConfigurationManager.AppSettings["TfsUrl"]);
            TfsUtil.UnSubscribeToCheckinEvent(tfsUri, _subscriptionIds);
            _hostService.Dispose();
            _tokenSource.Cancel();
            _tokenSource.Dispose();
            JobManager.Instance.Dispose();
        }
    }
}
